<template>
  <div class="app-container">
    <div v-show="!open">
      <el-form
        @submit.native.prevent
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="任务名称" prop="taskName">
          <el-input
            v-model="queryParams.taskName"
            placeholder="请输入任务名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="taskList">
        <el-table-column label="任务ID" prop="taskId" width="150" />
        <el-table-column label="任务名称" prop="taskName" />
        <el-table-column label="是否信创" prop="isXC">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isXc == true" type="danger" effect="plain">信创</el-tag>
            <el-tag v-else type="info" effect="plain">非信创</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="标题" prop="instanceName" />
        <el-table-column label="流程" prop="definitionName" />
        <el-table-column label="创建时间" prop="createTime" width="150" />
        <el-table-column label="状态" prop="state">
          <template slot-scope="scope">
            {{ scope.row.state }}
            <div
              v-if="scope.row.taskName == scope.row.definitionName || scope.row.taskName == '发起'"
              style="color: red"
            >
              （被驳回）
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-search"
              :loading="btnLoading"
              @click="showDetail(scope.row)"
              >审批</el-button
            >
            <el-button size="mini" type="text" icon="el-icon-time" :loading="btnLoading" @click="showHistory(scope.row)"
              >审批历史</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <div v-show="open" :title="title" :visible.sync="open" width="90%">
      <applyDetails :priceFlag="priceFlag" :form="form" v-if="definitionName == '资源申请'" />
      <changeDetails v-if="definitionName == '资源变更'" />
      <div class="title" style="margin-top: 30px">流程图</div>
      <Process ref="process" style="margin-bottom: 10px" />
      <div class="title" style="margin-top: 30px">审批流程</div>
      <div class="xx">
        <ul class="timeline-wrapper">
          <li class="timeline-item" v-for="t in timelineList" :key="t.id">
            <div class="timeline-box">
              <div class="out-circle">
                <div class="in-circle"></div>
              </div>
              <div class="long-line"></div>
            </div>
            <div class="timeline-content">
              <div class="box">
                <div class="timeline-title">{{ t.name }}</div>
                <div class="timeline-date">{{ t.time }}</div>
              </div>
              <div class="timeline-desc" style="margin-bottom: 10px">
                {{ t.assigneeName }} <span :style="ActionColorStatus(t.action)">{{ t.actionName }}</span>
              </div>
              <div class="timeline-desc" v-if="t.action">审批意见：{{ t.comment }}</div>
            </div>
          </li>
        </ul>
      </div>
      <applyButton
        v-if="definitionName == '资源申请'"
        @openClose="openClose"
        :taskId="taskId"
        :taskName="taskName"
        :detail="form"
      />
      <changeButton
        v-if="definitionName == '资源变更'"
        @openClose="openClose"
        :taskId="taskId"
        :taskName="taskName"
        :detail="form"
      />
    </div>

    <el-dialog :title="title" :visible.sync="openHistory" width="90%">
      <el-table v-loading="historyLoading" :data="historyList">
        <el-table-column label="ID" width="100" prop="id" />
        <el-table-column label="节点" prop="name" />
        <el-table-column label="处理人" prop="assigneeName" />
        <el-table-column label="开始时间" prop="startTime" />
        <el-table-column label="结束时间" prop="endTime" />
        <el-table-column label="处理方式" prop="actionName" />
        <el-table-column label="意见" prop="comment" />
      </el-table>
      <pagination
        v-show="historyTotal > 0"
        :total="historyTotal"
        :page.sync="historyParams.pageNum"
        :limit.sync="historyParams.pageSize"
        @pagination="getHistory"
      />
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import { taskTodoList } from "@/api/todoItem/todo.js";
import { listHistory } from "@/api/activiti/example.js";

import { instId, serviceByClazz, listByCode, formResourceUp } from "@/api/resources/apply.js";

import { getChangeDetail } from "@/api/resources/change.js";
import { getDicts } from "@/api/system/dict/data";

import Details from "./details.vue";
import applyDetails from "../../resources/apply/addC.vue";
import applyButton from "../../resources/apply/button.vue";

import changeDetails from "../../resources/change/details.vue";
import changeButton from "../../resources/change/button.vue";

import Process from "./process.vue";
export default {
  name: "Todo",
  components: {
    Process,
    Details,

    applyDetails,
    applyButton,

    changeDetails,
    changeButton,
  },
  data() {
    return {
      timelineList: [],
      // 遮罩层
      loading: true,
      btnLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 待办表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 显示/隐藏审批历史
      openHistory: false,
      // 审批历史遮罩层
      historyLoading: false,
      // 审批历史列表
      historyList: [],
      // 审批历史列表数量
      historyTotal: 0,

      // 审批历史查询参数
      historyParams: {
        pageNum: 1,
        pageSize: 10,
        // taskId: null,
        // taskName: null,
      },
      // 任务id
      taskId: "",
      // 流程
      definitionName: "",
      // 节点
      taskName: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // taskId: null,
        // taskName: null,
      },

      // 表单校验
      rules: {},

      //数据详情
      form: {},
      //配置
      configure: {
        available_domain: [], //可用域
        cloud_service_provider: [], //服务商
        storage_type: [], //系统盘类型
        codeList: [], //云服务器规格列表
        czxtList: [], //操作系统列表
        ccList: [], //数据盘类型
        fwcpList: [], //服务型磁盘类型
        wlfwqList: [], //高性能服务器资源类型
        sjkList: [], //数据库类型
        yyaqList: [], //安全产品
      },
      //是否显示预估费用
      priceFlag: false,
    };
  },
  created() {
    // this.getDicts();
    this.getList();
    // this.getDataOfAdd();
  },
  watch: {
    $route(route) {
      if (route.fullPath == "/todoItem/todo") {
        this.getList();
      }
    },
  },
  methods: {
    // 返回审核意见颜色状态
    ActionColorStatus(name) {
      if (name == "COMPLETE") {
        return `margin-left: 10px;color : #008000`;
      } else if (name == "BACK") {
        return `margin-left: 10px;color : #ffff00`;
      } else if (name == "REJECT") {
        return `margin-left: 10px;color : #ffff00`;
      } else if (name == "DELEGATE") {
        return `margin-left: 10px;color : #ffff00`;
      } else if (name == "JUMP") {
        return `margin-left: 10px;color : #ffff00`;
      } else if (name == "DELETE") {
        return `margin-left: 10px;color : #ff0000`;
      } else {
        return `margin-left: 10px;`;
      }
    },
    //获取配置信息
    getDicts() {
      for (let item in this.configure) {
        getDicts(item).then((response) => {
          this.configure[item] = response.data;
        });
      }
    },

    //关闭弹窗
    openClose(flag) {
      this.open = false;
      if (flag) {
        this.getList();
      }
    },
    // 审批历史查询
    formResourceUps(id) {
      formResourceUp(id).then((res) => {
        this.timelineList = res.rows;
      });
    },
    //显示详情-----------------------------------------------
    showDetail(data) {
      this.title = data.taskName;
      this.taskId = data.taskId;
      this.definitionName = data.definitionName;
      this.taskName = data.taskName;

      if (data.definitionName == "资源申请") {
        // this.formResourceUps(data.instanceId)
        this.instIdDetail(data);
        // instanceId
      } else if (data.definitionName == "资源变更") {
        // this.formResourceUps(data.instanceId)
        this.changeDetail(data);
      } else if (data.definitionName == "ip资源管理 ") {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("IPResourceManager", arr);
        this.$router.push("/resources/IPResourceManagers/details");
      } else if (data.definitionName == "应用故障") {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("ApplicationFailures", arr);
        this.$router.push("/faultdeclara/ApplicationFailures/details");
      } else if (data.definitionName == "操作系统故障") {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("systemFailures", arr);
        this.$router.push("/faultdeclara/systemFailures/details");
      } else if (data.definitionName == "网络故障") {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("NetworkFailures", arr);
        this.$router.push("/faultdeclara/NetworkFailures/details");
      } else if (data.definitionName == "云平台故障") {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("CloudFailures", arr);
        this.$router.push("/faultdeclara/CloudFailures/details");
      } else if (data.definitionName == "安全故障") {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("SafetyFailures", arr);
        this.$router.push("/faultdeclara/SafetyFailures/details");
      } else if (data.definitionName == "数据交互") {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("ArrayInteractions", arr);
        this.$router.push("/businessassistance/ArrayInteractions/details");
      } else if (data.definitionName == "端口管理") {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("InterfaceManagements", arr);
        this.$router.push("/businessassistance/InterfaceManagements/details");
      } else if (data.definitionName == "访问权限") {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("AccessRights", arr);
        this.$router.push("/businessassistance/AccessRightss/details");
      } else if (data.definitionName == "进出机房") {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("InOutComputerRooms", arr);
        this.$router.push("/businessassistance/InOutComputerRooms/details");
      } else if (data.definitionName == "系统升级/变更" || data.definitionName == "系统重装/升级") {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("SystemUpgrades", arr);
        this.$router.push("/businessassistance/SystemUpgrades/details");
      } else if (data.definitionName == "托管设备上下架") {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("ManagedDevices", arr);
        this.$router.push("/businessassistance/ManagedDevices/details");
      } else if (data.definitionName == "压力/安全测试") {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("PressureSafetyTests", arr);
        this.$router.push("/businessassistance/PressureSafetyTests/details");
      } else if (data.definitionName == "域名备案") {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("DomainNameFilings", arr);
        this.$router.push("/businessassistance/DomainNameFilings/details");
      } else if (data.definitionName == "找回备案号密码") {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("RetrieveRecordPasswords", arr);
        this.$router.push("/businessassistance/RetrieveRecordPasswords/details");
      } else if (data.definitionName == "其他事项") {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("OtherMatterss", arr);
        this.$router.push("/businessassistance/OtherMatterss/details");
      } else if (data.definitionName == "退云流程") {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("retreatCloudsExamine", arr);
        this.$router.push("/resources/retreatClouds/examine/" + data.instanceId);
      }
    },
    // 查询资源申请详情
    instIdDetail(dat) {
      // 信创申请
      if (dat.isXc) {
        var arr = JSON.stringify(dat);
        sessionStorage.setItem("DetailsAgency", arr);
        this.$router.push("/todoItem/todoS/DetailsAgency");
      } else {
        var arr = JSON.stringify(dat);
        sessionStorage.setItem("DetailsAgencyNoXc", arr);
        this.$router.push("/todoItem/todoS/DetailsAgencyNoXc");
      }

      // this.$router.push("/todoItem/todoS/DetailsAgency?obj=" + encodeURIComponent(arr));
      return;
      this.btnLoading = true;
      let ifStatistic = "false";
      if (["监管平台接收", "监管平台初核", "大数据中心复核", "监管平台派发"].indexOf(dat.taskName) > -1) {
        ifStatistic = "true";
        this.priceFlag = true;
      } else {
        this.priceFlag = false;
      }
      instId({ ifStatistic, id: dat.instanceId })
        .then((res) => {
          let detail = res.data;
          this.configure.cloud_service_provider.some((item) => {
            if (item.dictValue == detail.cloudSupplier) {
              detail.cloudSupplier_label = item.dictLabel;
              return true;
            }
          });
          detail.storeProducts.forEach((data) => {
            this.configure[data.productCode == "共享型" ? "ccList" : "fwcpList"].some((it) => {
              if (it.code == data.diskServerCode) {
                data.diskServerCode_label = it.serviceName;
                return true;
              }
            });
            data.hostInstanceNames = [];
            if (data.hosts) {
              data.hosts.forEach((item) => {
                data.hostInstanceNames.push(item.instanceName);
              });
            }
          });
          detail.databases.forEach((data) => {
            this.configure.sjkList.some((it) => {
              if (it.code == data.serverCode) {
                data.serverCode_label = it.serviceName;
                return true;
              }
            });
          });
          detail.hosts.forEach((data) => {
            data.hostName = data.instanceName;
            //可用域
            this.configure.available_domain.some((item) => {
              if (item.dictValue == data.availableDomain) {
                data.availableDomain_label = item.dictLabel;
                return true;
              }
            });
            //数据盘类型
            if (data.disks && data.disks.length) {
              data.disks.forEach((item) => {
                this.configure.ccList.some((it) => {
                  if (it.code == item.diskServerCode) {
                    item.diskServerCode_label = it.serviceName;
                    return true;
                  }
                });
              });
            } else {
              data.disks = [];
            }
            if (data.flavorType == 1) {
              //系统盘类型
              if (data.osDisk) {
                this.configure.storage_type.some((item) => {
                  if (item.code == data.osDisk.diskServerCode) {
                    data.osDisk.diskServerCode_label = item.serviceName;
                    return true;
                  }
                });
              }
              this.configure.codeList.some((item) => {
                console.log(item, 111);
                if (item.specCode == data.cloudFlavorCode) {
                  data.cloudFlavorCode_label = item.specName;
                  data.cloudFlavorCode_desc = item.desc;
                  return true;
                }
              });
            }
            if (data.flavorType == 2) {
              this.configure.wlfwqList.some((item) => {
                if (item.code == data.cloudFlavorCode) {
                  data.cloudFlavorCode_label = item.serviceName;
                  data.cloudFlavorCode_desc = item.remark;
                  return true;
                }
              });
            }
          });
          console.log(detail.hosts, 4545);
          setTimeout(() => {
            this.form = detail;
            this.form.ifStatistic = ifStatistic == "true" ? true : false;
            this.open = true;

            this.$refs.process.init(dat);
          }, 200);
        })
        .finally(() => {
          this.btnLoading = false;
        });
    },
    // 查询资源变更详情
    changeDetail(data) {
      // 信创变更
      if (data.isXc) {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("ChangeDetailsAgency", arr);
        this.$router.push("/todoItem/todoS/ChangeDetailsAgency");
      } else {
        var arr = JSON.stringify(data);
        sessionStorage.setItem("ChangeDetailsAgencyNoXc", arr);
        this.$router.push("/todoItem/todoS/ChangeDetailsAgencyNoXc");
      }

      // this.$router.push("/todoItem/todoS/ChangeDetailsAgency?obj=" + encodeURIComponent(arr));
      return;
      getChangeDetail(data.instanceId).then((response) => {
        this.form = response.data;
        this.open = true;
        setTimeout(() => {
          this.$refs.process.init(data);
        }, 500);
      });
    },

    //获取一些配置数据
    getDataOfAdd() {
      //可用域
      getDicts("available_domain").then((response) => {
        this.configure.available_domain = response.data;
      });
      //服务商
      getDicts("cloud_service_provider").then((response) => {
        this.configure.cloud_service_provider = response.data;
      });
      //盘类型
      serviceByClazz({ code: "cc" }).then((response) => {
        response.data.forEach((item) => {
          if (["FCcc(tykcc)2", "FCcc_ssd", "spycc2"].indexOf(item.code) < 0) {
            this.configure.storage_type.push(item);
          }
          if (["spycc2"].indexOf(item.code) < 0) {
            this.configure.ccList.push(item);
          }
          if (["fbscc_wjcc2", "FCcc(tykcc)2", "FCcc_ssd"].indexOf(item.code) < 0) {
            this.configure.fwcpList.push(item);
          }
        });
      });
      //操作系统
      serviceByClazz({ code: "czxt" }).then((response) => {
        this.configure.czxtList = response.data;
      });
      //云服务器规格列表
      listByCode("spec_ecs").then((response) => {
        this.configure.codeList = response.data;
      });
      //高性能服务器资源类型列表
      serviceByClazz({ code: "wlfwq" }).then((response) => {
        this.configure.wlfwqList = response.data;
      });
      //数据库类型列表
      serviceByClazz({ code: "sjk" }).then((response) => {
        this.configure.sjkList = response.data;
      });
      //安全产品列表
      serviceByClazz({ code: "yyaq" }).then((response) => {
        this.configure.yyaqList = response.data;
      });
    },

    /** 查询审批历史 */
    showHistory(data) {
      this.historyList = [];
      this.title = data.taskName;
      this.openHistory = true;
      this.historyParams = {
        pageNum: 1,
        pageSize: 10,
        processInstanceId: data.instanceId,
      };
      this.getHistory();
    },
    getHistory() {
      this.btnLoading = true;
      this.historyLoading = true;
      listHistory(this.historyParams)
        .then((response) => {
          this.historyList = response.rows;
          this.historyTotal = response.total;
          this.historyLoading = false;
        })
        .finally(() => {
          this.btnLoading = false;
        });
    },

    /** 查询待办列表 */
    getList() {
      this.loading = true;
      taskTodoList(this.queryParams).then((response) => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskId: null,
        taskName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.taskName = "";
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加待办";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getDemo(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改待办";
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.el-table {
  color: #000;
}
.title {
  text-align: left;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: bold;
  padding-left: 4px;
  border-left: 4px solid #38b3aa;
}
.xx {
  ul.timeline-wrapper {
    list-style: none;
    margin: 0;
    padding: 0;
  }

  /* 时间线 */
  .timeline-item {
    position: relative;

    .timeline-box {
      text-align: center;
      position: absolute;

      .out-circle {
        width: 16px;
        height: 16px;
        background: rgba(14, 116, 218, 0.1);
        box-shadow: 0px 4px 12px 0px rgba(0, 0, 0, 0.1);
        /*opacity: 0.1;*/
        border-radius: 50%;
        display: flex;
        align-items: center;

        .in-circle {
          width: 8px;
          height: 8px;
          margin: 0 auto;
          background: rgba(14, 116, 218, 1);
          border-radius: 50%;
          box-shadow: 0px 4px 12px 0px rgba(0, 0, 0, 0.1);
        }
      }

      .long-line {
        width: 2px;
        height: 98px;
        background: rgba(14, 116, 218, 1);
        box-shadow: 0px 4px 12px 0px rgba(0, 0, 0, 0.1);
        opacity: 0.1;
        margin-left: 8px;
      }
    }

    .timeline-content {
      box-sizing: border-box;
      margin-left: 20px;
      height: auto;
      padding: 0 0 0 20px;
      text-align: left;
      margin-bottom: 30px;
      .box {
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        .timeline-title {
          font-size: 18px;
          // word-break: break-all;
          color: #333;
          font-weight: 500;
          /*display: inline;*/
        }

        .timeline-date {
          margin-left: 50px;
          font-size: 16px;
          color: #333;
          font-weight: 500;
        }
      }
      .timeline-desc {
        font-size: 14px;
        margin-bottom: 10px;
        color: #999999;
      }
    }
  }

  .timeline-item:last-of-type .timeline-content {
    margin-bottom: 0;
  }
}
</style>
